import { css } from './styles.js';
import { render } from './html.js';
import { router } from '../../common/router.js';

class RightBody extends HTMLElement {
    constructor() {
        super();

        this.attachShadow({ mode: 'open' });

        this.shadowRoot.innerHTML = `
            <style>${css}</style>
            ${render()}
        `;

        // 监听路由变化事件
        this.bindRouteEvents();
    }

    bindRouteEvents() {
        // 监听自定义路由变化事件
        window.addEventListener('route-change', () => {
            this.updateContent();
        });

        // 监听浏览器前进后退
        window.addEventListener('popstate', () => {
            this.updateContent();
        });
    }

    updateContent() {
        const rightBodyDiv = this.shadowRoot.querySelector('.right-body');
        if (rightBodyDiv) {
            // 保留nav-bar，只更新路由内容
            const navBar = rightBodyDiv.querySelector('nav-bar');
            rightBodyDiv.innerHTML = `${navBar ? navBar.outerHTML : '<nav-bar></nav-bar>'}${router()}`;
        }
    }
}

window.customElements.define('right-body', RightBody);
